import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:verse_systems/commom/global/global.dart';
import 'package:verse_systems/commom/models/product_model.dart';
import 'package:verse_systems/pages/home/home_control.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/utils/image_utils.dart';
import 'package:verse_systems/utils/images_path.dart';
import 'package:verse_systems/widgets/customize_home_appbar.dart';
import 'package:marquee/marquee.dart';
import 'package:verse_systems/widgets/product_item.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final control = Get.put(HomeControl());
  final state = Get.find<HomeControl>().state;

  @override
  void initState() {
    super.initState();
    control.getAppHomeInfoList();
  }

  List<Widget> _wrapList() {
    final List<Widget> listWidget = state.items.map((val) {
      return InkWell(
          highlightColor: Colors.transparent,
          radius: 0.0,
          onTap: () async {
            debugPrint("跳转链接--${val["title"]}");
          },
          child: Container(
            width: MediaQuery.of(context).size.width / 3,
            padding: const EdgeInsets.symmetric(vertical: 20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 15.w),
                Image.asset(
                  val["path"],
                  fit: BoxFit.fill,
                  width: 42.w,
                  height: 42.w,
                ),
                SizedBox(height: 14.w),
                Text(
                  val["title"],
                  style: TextStyle(
                      color: Colours.app_black_text_color,
                      fontSize: 11.sp,
                      fontWeight: FontWeight.w600),
                ),
              ],
            ),
          ));
    }).toList();
    return listWidget;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colours.system_background_color,
        body: GetBuilder<HomeControl>(
            init: control,
            builder: (_) {
              return CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(
                      child: CustomizeHomeAppbar(
                    title: state.title,
                    placard: state.placard,
                    amount: state.amount,
                    callBack: control.jumpToAuthen,
                  )),
                  SliverToBoxAdapter(
                      child: MessageBar(
                    title: state.notice.join(","),
                  )),
                  SliverToBoxAdapter(
                    child: Row(children: _wrapList()),
                  ),
                  SliverToBoxAdapter(
                      child: (state.productInfoList.isEmpty)
                          ? const EmptyPage()
                          : Container(
                              margin: EdgeInsets.symmetric(
                                  vertical: 10.w,
                                  horizontal:
                                      (MediaQuery.of(context).size.width -
                                              330.w) /
                                          2),
                              child: Row(
                                children: [
                                  Container(
                                    margin: EdgeInsets.only(right: 5.w),
                                    width: 4.w,
                                    height: 15.w,
                                    color: Colours.app_home_tag_color,
                                  ),
                                  Text(
                                    "recommendation".tr,
                                    style: TextStyle(
                                      color: Colours.app_black_text_color,
                                      fontSize: 14.sp,
                                    ),
                                  ),
                                ],
                              ),
                            )),
                  SliverList(
                      delegate: SliverChildBuilderDelegate((context, index) {
                    ProductModel model = state.productInfoList[index];
                    return ProductItem(
                        model: model,
                        onPressed: () {
                          debugPrint(model.name);
                          control.jumpProductWeb(
                              productID: model.id.toString());
                        });
                  }, childCount: state.productInfoList.length)),
                  SliverToBoxAdapter(child: SizedBox(height: 30.w)),
                ],
              );
            }));
  }
}

class MessageBar extends StatelessWidget {
  final String? title;
  const MessageBar({super.key, this.title = ""});

  @override
  Widget build(BuildContext context) {
    return (title == "")
        ? Container()
        : Container(
            height: 35.w,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10.w),
            margin: EdgeInsets.symmetric(
                horizontal: (MediaQuery.of(context).size.width - 330.w) / 2),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(10.w)),
              color: Colours.app_msg_color,
            ),
            child: Row(
              children: [
                Image.asset(
                  IMagesPath.getHomeNotifications(),
                  fit: BoxFit.fill,
                  width: 20.w,
                  height: 18.w,
                ),
                SizedBox(width: 5.w),
                SizedBox(
                  width: 280.w,
                  child: Marquee(
                    text: '$title',
                    // 文本样式
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 12.sp,
                        color: Colours.app_msg_text_color),
                    // 滚动轴：水平或者竖直
                    scrollAxis: Axis.horizontal,
                    // 轴对齐方式start
                    crossAxisAlignment: CrossAxisAlignment.start,
                    // 空白间距
                    blankSpace: 20.0,
                    // 速度
                    velocity: 50.0,
                    // 暂停时长
                    pauseAfterRound: const Duration(seconds: 2),
                    // startPadding
                    startPadding: 5.0,
                    // 加速时长
                    // accelerationDuration: const Duration(seconds: 2),
                    accelerationDuration: const Duration(seconds: 5),
                    // 加速Curve
                    accelerationCurve: Curves.linear,
                    // 减速时长 const Duration(milliseconds: 800),
                    decelerationDuration: const Duration(seconds: 5),
                    // 减速Curve
                    decelerationCurve: Curves.easeOut,
                  ),
                )
              ],
            ));
  }
}

class EmptyPage extends StatelessWidget {
  const EmptyPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: EdgeInsets.symmetric(horizontal: 15.w),
        child: Container(
          decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(10.w)),
                  color: Colours.app_main_color,
            ),
          child: Column(
            children: [_userWary, _likeFavorite],
          ),
        ));
  }

  Widget get _likeFavorite {
    return Container(
        margin: EdgeInsets.symmetric(vertical: 10.w),
        child: Wrap(
            alignment: WrapAlignment.start,
            runSpacing: 5.w,
            spacing: 5.w,
            children: _likeView));
  }

  List<Widget> get _likeView {
    return [
      {
        "title": "high_reserves".tr,
        "text": "up_to_amount".tr,
        "path": ImageUtils.getModuleImgPath("empty_reserve")
      },
      {
        "title": "loan_discounts".tr,
        "text": "loan_upper_discount".tr,
        "path": ImageUtils.getModuleImgPath("empty_rebate")
      },
      {
        "title": "member_center".tr,
        "text": "enjoy_privileges".tr,
        "path": ImageUtils.getModuleImgPath("empty_associator")
      },
      {
        "title": "rational_protection".tr,
        "text": "complaint_channels".tr,
        "path": ImageUtils.getModuleImgPath("empty_complaints")
      },
    ].map((val) {
      return Container(
          padding: EdgeInsets.fromLTRB(15.w, 15.w, 0, 15.w),
          width: 165.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5.w)),
            color: Colours.app_image_background_color,
            image: DecorationImage(
                image: ExactAssetImage(val["path"].toString()),
                fit: BoxFit.contain),
          ),
          child: Column(
            crossAxisAlignment :CrossAxisAlignment.start,
            mainAxisAlignment : MainAxisAlignment.center,
            children: [
              Text(
                val["title"].toString(),
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.black,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Text(
                val["text"].toString(),
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colours.app_text_color,
                ),
              ),
            ],
          ));
    }).toList();
  }

  Widget get _userWary {
    BuildContext context = Global.navigatorKey.currentState!.overlay!.context;
    return Container(
        padding: EdgeInsets.symmetric(vertical: 20.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: MediaQuery.of(context).size.width - 136.w,
              margin: EdgeInsets.symmetric(horizontal: 10.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "wary_money_transfers".tr,
                    style: TextStyle(
                      fontSize: 20.sp,
                      color: Colors.black,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text.rich(TextSpan(children: [
                    TextSpan(
                      text: "whereever".tr,
                      style: TextStyle(
                          fontSize: 14.sp, color: Colours.app_text_color),
                    ),
                    TextSpan(
                      text: "express_accounts".tr,
                      style: TextStyle(
                        color: Colours.app_main_text_color,
                        fontSize: 14.sp,
                      ),
                    ),
                    TextSpan(
                      text: "transfers_scams".tr,
                      style: TextStyle(
                          fontSize: 14.sp, color: Colours.app_text_color),
                    ),
                  ])),
                ],
              ),
            ),
            Image.asset(
              ImageUtils.getModuleImgPath("empty_iocn"),
              fit: BoxFit.fill,
              width: 86.w,
              height: 75.w,
            )
          ],
        ));
  }
}
